//
//  ViewController+Interface.m
//  SiriShortcuts
//
//  Created by orvibo on 2018/12/25.
//  Copyright © 2018 orvibo. All rights reserved.
//

#import "ViewController+Interface.h"

@implementation ViewController (Interface)

-(NSArray *)interfaceArray{

    return [@[
              
              @{@"name":@"45 商品（服务包）查询接口",@"selector":^{
        [self testQueryItems:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              @{@"name":@"44 查询订单支付状态",@"selector":^{
        [self testQueryOrderStatus:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              @{@"name":@"43 创建订单(微信支付)",@"selector":^{
        [self testCreateTraceOrderWithWX:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              @{@"name":@"42 MixPad音乐服务是否开通查询",@"selector":^{
        [self testMixpadServiceIsAct:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              @{@"name":@"41 基础服务查询接口",@"selector":^{
        [self testMixpadBaseService:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              
              @{@"name":@"40 激活音乐服务",@"selector":^{
        [self testActMusicService:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
              @{@"name":@"39 蓝牙音箱和mixPad激活查询",@"selector":^{
        [self testMixpadActQuery:^(KReturnValue returnValue, NSDictionary *returnDic) {
            
        }];
    }},
             
             ]mutableCopy];
}

-(NSString *)uid{
    return @"0fcdd2da9d6841e69fa35eedacedc563";
}
-(NSString *)blueExtAddr{
    return @"F44EFD000001";
}
-(NSString *)userId{
    return userAccout().userId;
}



//43 创建订单(微信支付)
-(void)testCreateTraceOrderWithWX:(SocketCompletionBlock)block {
    
    NSString *uid = [self uid];
    NSString *itemId = @"default-pack-100100";// 商品id
    NSString *userId = [self userId];
    
    [self getAccessToken:^(NSString *token) {
        
        NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/order/createTraceOrderWithWX?itemId=%@&uid=%@&userId=%@&token=%@",itemId,uid,userId,token];
        [self requestURL:url delayTime:5.0 completion:^(KReturnValue returnValue, NSDictionary *dic) {
            
            
        }];
    }];
}

//44 查询订单支付状态
-(void)testQueryOrderStatus:(SocketCompletionBlock)block {
    
    NSString *traceNo = @"";// 订单号
    NSString *userId = [self userId];
    
    [self getAccessToken:^(NSString *token) {
        
        NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/order/queryOrderStatus?traceNo=%@&userId=%@&token=%@",traceNo,userId,token];
        [self requestURL:url delayTime:5.0 completion:^(KReturnValue returnValue, NSDictionary *dic) {
            
            
        }];
        
    }];
    
}


//45 商品（服务包）查询接口
-(void)testQueryItems:(SocketCompletionBlock)block {
    
    NSNumber *type = @(0); // 0表示音乐包
    NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/item/queryItems?type=%@",type];
    [self requestURL:url delayTime:5.0 completion:^(KReturnValue returnValue, NSDictionary *dic) {
        
        
    }];
}


//39. 蓝牙音箱和mixPad激活查询
-(void)testMixpadActQuery:(SocketCompletionBlock)block {
    
    NSString *uid = [self uid];
    NSString *blueExtAddr = [self blueExtAddr];
    
    // 只查蓝牙
    NSString *url1 = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/actQuery?blueExtAddr=%@",blueExtAddr];
    [self requestURL:url1 delayTime:5.0 completion:^(KReturnValue returnValue, NSDictionary *dic) {
        
        
    }];
    
    
    // 只查uid
    NSString *url2 = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/actQuery?uid=%@",uid];
    
    [self requestURL:url2 delayTime:5.0 completion:^(KReturnValue returnValue, NSDictionary *dic) {
        
        
    }];
    
    // uid&蓝牙一起查
    NSString *url3 = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/actQuery?uid=%@&blueExtAddr=%@",uid,blueExtAddr];
    
    [self requestURL:url3 delayTime:5.0 completion:block];
}

//40 激活音乐服务
-(void)testActMusicService:(SocketCompletionBlock)block{
    
    NSString *uid = [self uid];
    NSString *blueExtAddr = [self blueExtAddr];
    NSString *userId = [self userId];
    
    [self getAccessToken:^(NSString *token) {
       
        NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/act?uid=%@&blueExtAddr=%@&userId=%@&token=%@",uid,blueExtAddr,userId,token];
        [self requestURL:url delayTime:5.0 completion:block];
        
    }];
}

//41 基础服务查询接口
-(void)testMixpadBaseService:(SocketCompletionBlock)block{
    
    NSString *uid = [self uid];
    
    NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/service?uid=%@",uid];
    
    [self requestURL:url delayTime:5.0 completion:block];
}

//42 MixPad音乐服务是否开通查询
-(void)testMixpadServiceIsAct:(SocketCompletionBlock)block{
    
    NSString *uids = [NSString stringWithFormat:@"%@,%@,%@,%@",[self uid],[self uid],[self uid],[self uid]];
    
    NSString *url = [NSString stringWithFormat:@"https://homemate.orvibo.com/music/statusList?uids=%@",uids];
    
    [self requestURL:url delayTime:5.0 completion:block];
}


-(void)requestURL:(NSString *)URL delayTime:(NSTimeInterval) delayTime completion:(SocketCompletionBlock) completion{
    
    HMRequestBlock block = ^(NSData *data, NSURLResponse *response, NSError *err){
        
        if (completion) {
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                
                if (data) {
                    
                    NSError *error = nil;
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

                    if (error) {
                        NSLog(@"请求出错，error -- %@ dic = %@ \ndata = %@",error,dic,[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                        completion(KReturnValueFail,nil);
                    }else{
                        NSLog(@"\n\n发送请求：%@ \n\n返回结果：%@\n",URL,dic);
                        // 把有效的升级信息保存在本地
                        if (dic && [dic isKindOfClass:[NSDictionary class]]) {
                            
                            int code = [dic[@"code"]intValue];
                            if (code == 0) {
                                completion(KReturnValueSuccess,dic);
                            }else{
                                NSLog(@"服务器返回错误码：%d",code);
                                completion(code,dic);
                            }
                        }else{
                            completion(KReturnValueFail,nil);
                        }
                    }
                    
                }else{
                    NSLog(@"服务器返回数据为空，URL = %@ error = %@",URL,err);
                    completion(KReturnValueFail,nil);
                }
            });
        }
    };
    
    //默认会话配置
    NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForRequest= delayTime;//请求超时时间
    sessionConfig.allowsCellularAccess = YES;//是否允许蜂窝网络下载（2G/3G/4G）
    sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringCacheData; // 不使用缓存
    //创建会话，并指定配置和代理
    NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig];
    // 通过URL初始化task,在block内部可以直接对返回的数据进行处理
    NSURL *reqURL = [NSURL URLWithString:URL];
    NSURLSessionTask *task = [session dataTaskWithURL:reqURL completionHandler:block];
    
    // 启动任务
    [task resume];
}

-(void)getAccessToken:(void(^)(NSString *token))block{
    
    NSString *session= [RemoteGateway shareInstance].session;
    NSString *getTokenUrl = [NSString stringWithFormat:@"https://homemate.orvibo.com/getOauthToken?sessionId=%@",session];
    [self requestURL:getTokenUrl delayTime:5.0 completion:^(KReturnValue value, NSDictionary *dic) {
        if (value == KReturnValueSuccess) {
            
            int status = [dic[@"status"]intValue];
            if (status == 0) {
                
                NSDictionary *authDic = dic[@"data"];
                NSString *token = authDic[@"access_token"];
                if (block && token) {
                    block(token);
                    return;
                }
            }
        }
        DLog(@"！！！！！获取authToken失败");
    }];
}
@end
